package utils

import (
	"bytes"
	"io"
	"log"
	"net/http"
	"os"
	"reflect"
	"runtime"
	"strings"

	"github.com/pdfcpu/pdfcpu/pkg/api"
	"github.com/pdfcpu/pdfcpu/pkg/pdfcpu/model"
)

func CheckInitError(err error) {
	if err != nil {
		log.Panicln(err)
	}
}

// GetEnvName 需判空
func GetEnvName(key string) string {
	return os.Getenv(key)
}

func LastString(ss []string) string {
	return ss[len(ss)-1]
}

// GetFuncName 获取方法名 需判空
func GetFuncName() string {
	pc := make([]uintptr, 1)
	runtime.Callers(2, pc)
	return LastString(strings.Split(runtime.FuncForPC(pc[0]).Name(), "."))
}

// GetPFuncName 获取方法名包含包名点连接 需判空
func GetPFuncName() string {
	pc := make([]uintptr, 1)
	runtime.Callers(2, pc)
	return LastString(strings.Split(runtime.FuncForPC(pc[0]).Name(), "/"))
}

// GetPackageName 获取包名 需判空
func GetPackageName(em interface{}) string {
	return LastString(strings.Split(reflect.TypeOf(em).PkgPath(), "/"))
}

// IsValidPDF 判断是否为有效的PDF
func IsValidPDF(rs io.ReadSeeker) bool {
	config := model.NewDefaultConfiguration()
	config.ValidationMode = model.ValidationRelaxed
	err := api.Validate(rs, config)
	if err != nil {
		return false
	}
	return true
}

func IsValidMediaType(b []byte) bool {
	mime := http.DetectContentType(b)
	if strings.Contains(mime, "image/") ||
		strings.Contains(mime, "/pdf") ||
		strings.Contains(mime, "video/") ||
		IsValidPDF(bytes.NewReader(b)) {
		return true
	}
	return false
}
